<%@ page language="java" pageEncoding="utf-8"
	contentType="text/html;charset=utf-8"%>
<%@ include file="/WEB-INF/views/common.jsp"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>审批</title>
<link rel="stylesheet" type="text/css" href="/resources/css/approval.css" />

<link rel="stylesheet" type="text/css" href="/resources/css/jquery-ui.css" />

<script src="/resources/js/jquery.min.js" type="text/javascript" ></script>
<script src="/resources/js/jquery.validate.min.js" type="text/javascript"></script>
<script src="/resources/js/jquery.form.js" type="text/javascript"></script>
<script src="/resources/js/jquery.blockUI.js" type="text/javascript"></script>
<script src="/resources/js/jquery-ui.js" type="text/javascript"></script>


<script type="text/javascript">
jQuery.cachedScript = function(url, options) {
  options = $.extend(options || {}, {
    dataType: "script",
    cache: true,
    url: url
  });

  return jQuery.ajax(options);
};

$.approval = {
	//统一处理ajax调用错误信息
	ajaxerror:function(xhr){
		if(xhr.status == 401 ){
			if(confirm("超时，请重新登录！")){
				window.location.href = "/signin";
				return;
			}
		}else{
			alert("系统错误:" + xhr.status);
		}
	},
	
	errormsg:function(r){
		if(!r.result) {
			var errMsg = '';
			$.each(r.errors, function(key, value){
				errMsg += value + "\n";
			});
			alert(errMsg);
		}
		return r.result;
	},
	
	//描绘员工列表
	paintemployeetable : function(r){
		$("#checkAllEmployees").attr("checked", false);
		if(r.result) {
			var htmlStr = '';
			$.each(r.obj, function(i, info){
				htmlStr +='<ul class="detailline" id="ul_' + info.employee.employeeUUID + '">';
				htmlStr +='<li class="employee_titleheader_checkbox"><div class="titleheader_checkbox"><input type="checkbox" name="employeeUUID" id="employeeUUID_'+ info.employee.employeeUUID +'" value="'+ info.employee.employeeUUID +'"/></div></li>';
				htmlStr +='<li class="employee_titleheader_name"><div class="titleheader_font" id="employeename_' +info.employee.employeeUUID+ '">' + info.name + '</div></li>';
				htmlStr +='<li class="employee_titleheader_name"><div class="titleheader_font">' + info.employeeNO + '</div></li>';
				htmlStr +='<li class="employee_titleheader_name"><div class="titleheader_font">' + info.gender + '</div></li>';
				htmlStr +='<li class="employee_titleheader_mobile"><div class="titleheader_font">' + info.mobile + '</div></li>';
				htmlStr +='<li class="employee_titleheader_phone"><div class="titleheader_font">' + info.phone + '</div></li>';
				htmlStr +='<li class="employee_titleheader_email"><div class="titleheader_font">' + info.employee.userId + '</div></li>';
				htmlStr +='</ul>';
			});
			if(htmlStr == ''){
				htmlStr += '<ul class="detailline" id="ul_employeelist_empty">';
				htmlStr += '<li><div style="padding:20px;">暂无记录</div></li>';
				htmlStr += '</ul>';
			}
			$("#employeetable ul").remove("ul[class~='detailline']");
			$("#employeetable").append(htmlStr);
			$("#departmentpath").empty().append(r.objects['departmentPath']);
			$("#employeetable div[id^='employeename_']").on("click", function(event){
				var divId = $(this)[0].id;
				var employeeId = divId.substr(divId.indexOf("_") +1);
				$.ajax({
	    			type: 'POST',
					url: "/core/json/getemployeeinfo",
					data : { 
						"employeeUUID" : employeeId
					}, 
					success : function (r) {
						if(!$.approval.errormsg(r)){
							return ;
						}
					
						$("#area_employee_list").hide();
						$("#area_employee_create").show();
						
						$("#frmEmployee :input[name='employee.employeeUUID']").val(r.obj.employee.employeeUUID);
						$("#frmEmployee :input[name='employee.userId']").val(r.obj.employee.userId);
						$("#frmEmployee :input[name='name']").val(r.obj.name);
						$("#frmEmployee :input[name='gender'][value='"+r.obj.gender+"']").attr("checked", true);
						$("#frmEmployee :input[name='type'][value='"+r.obj.type+"']").attr("checked", true);
						$("#frmEmployee :input[name='employeeNO']").val(r.obj.employeeNO);
						$("#frmEmployee :input[name='rank']").val(r.obj.rank);
						$("#frmEmployee :input[name='mobile']").val(r.obj.mobile);
						$("#frmEmployee :input[name='phone']").val(r.obj.phone);
						$("#frmEmployee :input[name='business']").val(r.obj.business);
						$("#frmEmployee :input[name='identityCard']").val(r.obj.identityCard);
						$("#frmEmployee :input[name='calendarType'][value='"+r.obj.calendarType+"']").attr("checked", true);
						$("#frmEmployee :input[name='birth']").val(r.obj.birth);
						$("#frmEmployee :input[name='birthType'][value='"+r.obj.birthType+"']").attr("checked", true);
						$("#frmEmployee :input[name='marriage'][value='"+r.obj.marriage+"']").attr("checked", true);
						$("#frmEmployee :input[name='children'][value='"+r.obj.children+"']").attr("checked", true);
						$("#frmEmployee :input[name='departmentUUID']").val(r.obj.departmentUUID);
						
						$("#frmEmployee :input[name='operation']").val("update");
					},
					error: function(xhr) {
						$.approval.ajaxerror(xhr);
					}
	    		});
			});
			
			//checkbox events
			$("#employeetable").removeClass("jstree-draggable");
			$("#employeetable input:checkbox[name='employeeUUID']").click(function(){
				if($("#employeetable input:checked[name='employeeUUID']").length > 1){
					$("#employeetable ul[class~='detailline']").removeClass("jstree-draggable");
					$("#employeetable").addClass("jstree-draggable");
				}else{
					$("#employeetable input:checked[name='employeeUUID']").each(function(){
						$("#employeetable #ul_"+ $(this).val()).addClass("jstree-draggable");
					});
					$("#employeetable").removeClass("jstree-draggable");
				}
			});
		}else{
			var errMsg = '';
			$.each(r.errors, function(key, value){
				errMsg += value + "\n";
			});
			alert(errMsg);
		}//if(r.result) {
	}
}

$(function() {
	//处理左侧菜单
	$("#approvalmenus > div").click(function(event){
			var menuId = event.target.id;
			menuClick(menuId);
	});
	
	//构件新增审批界面
	$("#newApproval").click(function(){
		$("#mainconsole").empty();
		$("#mainconsole").load("/core/static/newApproval", {}, function(){
			//所见即所得输入框
			jQuery.cachedScript("/resources/tiny_mce/jquery.tinymce.js").done(function(){
				$('textarea.tinymce').tinymce({
		                // Location of TinyMCE script
		                script_url : '/resources/tiny_mce/tiny_mce.js',
		
		                // General options
		                theme : "advanced",
		                plugins : "table,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,print,contextmenu,directionality,fullscreen,noneditable,xhtmlxtras,template",
		
		                // Theme options
		                theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,formatselect,fontselect,fontsizeselect,|,forecolor,backcolor,|,link,unlink,|,sub,sup,|,charmap,emotions,iespell,insertdate,hr,image,template",
		                theme_advanced_buttons2 : "bullist,numlist,|,outdent,indent,blockquote,|,justifyleft,justifycenter,justifyright,justifyfull,|,ltr,rtl,|,tablecontrols,|,removeformat,code,preview,print,fullscreen",
		                theme_advanced_buttons3 : "",
		                theme_advanced_buttons4 : "",
		                theme_advanced_toolbar_location : "top",
		                theme_advanced_toolbar_align : "left",
		                theme_advanced_statusbar_location : "bottom",
		                theme_advanced_resizing : false,
		                width:"100%",
		                height:"300px",
		
		                // Example content CSS (should be your site CSS)
		                content_css : "css/content.css",
		
		                // Drop lists for link/image/media/template dialogs
		                template_external_list_url : "lists/template_list.js",
		                external_link_list_url : "lists/link_list.js",
		                external_image_list_url : "lists/image_list.js",
		
		                // Replace values for the template plugin
		                template_replace_values : {
		                        username : "Some User",
		                        staffid : "991234"
		                }
		        });
			});
			
			//审批路径地址栏
			var addressLines = new Array();
			var selectedAddressLines = [];
			 $( "#approvaladdress" ).selectable({
				 placeholder: "address_line",
				 stop: function(){
				 	selectedAddressLines.length = 0;
				 	$( ".ui-selected", this ).each(function() {
						var index = $( "#selectable li" ).index( this );
						selectedAddressLines.putsh(index);
					});
				 }
			 });	
			
			//事件注册
			$( "#approvalLineUserId" ).autocomplete({
				source: [ "c++", "java", "php", "coldfusion", "javascript", "asp", "ruby" ]
			});
			
			//POPUP职员搜索对话框
			$( "#employeelistresult" ).dialog({ 
				autoOpen: false,
				width: 600,
				height: 400,
				title: "职员列表"
			});
			$( "#btnPopupSearchEmployeesForApprovalLine" ).click(function(){
				$( "#employeelistresult" ).dialog("open");
			});
			
			//关键字查询
			$("#btnSearchEmployeesForApprovalLine").click(function(){
				var searchKeyword = $("#searchEmployeeByKeyword").val();
				if(searchKeyword == '')
					return;
					
				$.ajax({
	    			type: 'POST',
					url: "/core/json/listemployeeinfo",
					data : { 
						"departmentUUID" : '',
						'keyword' : searchKeyword
					}, 
					beforeSend : function(){
						$('#employeelistresult').block({ 
							message: '<div><img src="/resources/image/indicator_search.gif" /> <br/><br/> 正在进行数据查询...</div>',
							css : {width:'300px', 'font-size':'14px', padding:'10px'}
						});
					},
					success : function (r) {
						$('#employeelistresult').unblock();
						if(r.result) {
							var htmlStr = '';
							$.each(r.obj, function(i, info){
								htmlStr +='<ul class="detailline" id="ul_' + info.employee.employeeUUID + '">';
								htmlStr +='<li class="employee_titleheader_name"><div class="titleheader_font" id="employeename_' +info.employee.employeeUUID+ '">' + info.name + '</div></li>';
								htmlStr +='<li class="employee_titleheader_phone"><div class="titleheader_font">' + info.phone + '</div></li>';
								htmlStr +='<li class="employee_titleheader_mobile"><div class="titleheader_font">' + info.mobile + '</div></li>';
								htmlStr +='<li class="employee_titleheader_department"><div class="titleheader_font" id="department_' +info.employee.employeeUUID+ '">' + '--' + '</div></li>';
								htmlStr +='</ul>';
							});
							if(htmlStr == ''){
								htmlStr += '<ul class="detailline" id="ul_employeelist_empty">';
								htmlStr += '<li><div style="padding:20px;">暂无记录</div></li>';
								htmlStr += '</ul>';
							}
							$("#pop_employeetable ul").remove("ul[class~='detailline']");
							$("#pop_employeetable").append(htmlStr);
							
							$("#employeetable div[id^='employeename_']").on("click", function(event){
								var divId = $(this)[0].id;
								var employeeId = divId.substr(divId.indexOf("_") +1);
								var employeeName = $("#employeename_" + employeeId).text();
								var department = $("#department_" + employeeId).text();
								
							});
						}
					},
					error: function(xhr) {
						$('#employeelistresult').unblock();
						$.approval.ajaxerror(xhr);
					}
	    		}); //end ajax
			});
			
			//--
			
			
		});
	});
	
});

//处理左侧菜单点击事件
function menuClick(menuId){

	//员工管理
	if(menuId == "menu_department"){
		$("#mainconsole").empty();
		$("#mainconsole").load("/core/static/department", {}, function(response, status, xhr){
			if(xhr.status == 401 ){
				alert("超时，请重新登录！");
				window.location.href = "/signin";
				return;
			}
			jQuery.cachedScript("/resources/js/jquery.jstree.js").done(function(){
				$.getJSON("/core/json/companydepartment", function(treedata){
					$("#departmentTree").jstree({
			    		"json_data" :{
			    			"data"	: treedata,
			    			"correct_state" : false
			    		},
			    		"dnd" : {
			    			"drag_finish" : function (data) {
			    				var checkId = $(data.o).parents(".jstree-draggable").attr("id");
			    				var employeeUUIDS = "";
			    				if(checkId.indexOf("ul_") != -1){
			    					employeeUUIDS = checkId.substr(3);
			    				}else{
			    					$(data.o).parents(".jstree-draggable").children("ul[id^='ul_']").each(function(index, obj){
			    						employeeUUIDS += $(obj).attr("id").substr(3) +",";
			    					});
			    				}
			    				var destDepartmentUUID = data.r.attr("id");
			    				var srcDepartmentUUID = selectedDepartmentUUID;
			    				$.ajax({
					    			type: 'POST',
									url: "/core/json/moveemployeedepartment",
									data : { 
										"employeeUUIDS" : employeeUUIDS,
										"destDepartmentUUID" : destDepartmentUUID,
										"srcDepartmentUUID" : srcDepartmentUUID
									}, 
									success : function (r) {
										$.approval.paintemployeetable(r);
									},
									error: function(xhr) {
										$.approval.ajaxerror(xhr);
									}
					    		});
			    			}
			    		},
			    		"plugins" : [ "themes", "json_data", "ui" ,"crrm", "dnd"],
			    		"themes" : {
			    			"theme"	: "default",
			    			"url"	: "/resources/js/themes/default/style.css"
			    		}
			    	})
			    	.bind("select_node.jstree", function (event, data){
			    		var departmentUUID = data.rslt.obj[0].id;
			    		selectedDepartmentUUID = departmentUUID;
			    		$("#frmEmployee :input[name='departmentUUID']").val(departmentUUID);
			    		$.ajax({
			    			type: 'POST',
							url: "/core/json/listemployeeinfo",
							data : { 
								"departmentUUID" : departmentUUID
							}, 
							success : function (r) {
								$.approval.paintemployeetable(r);
							},
							error: function(xhr) {
								$.approval.ajaxerror(xhr);
							}
			    		});
			    		$("#area_employee_list").show();
						$("#area_employee_create").hide();
			    	})
			    	.bind("create.jstree", function (event, data) {
			    		$.ajax({
			    			type: 'POST',
							url: "/core/json/createdepartment",
							data : { 
								"parentDepartment.departmentUUID" : (data.rslt.parent === -1)?"":data.rslt.parent[0].id, 
								"sort" : data.rslt.position,
								"title" : data.rslt.name
							}, 
							success : function (r) {
								if(r.result) {
									$(data.rslt.obj).attr("id", r.obj.departmentUUID);
								}
								else {
									$.jstree.rollback(data.rlbk);
								}
							},
							error: function(xhr) {
								$.approval.ajaxerror(xhr);
							}
			    		});
			    	})
			    	.bind("remove.jstree", function (e, data) {
			    		data.rslt.obj.each(function () {
							$.ajax({
								async : false,
								type: 'POST',
								url: "/core/json/removedepartment",
								data : { 
									"departmentUUID" : $(this)[0].id
								}, 
								success : function (r) {
									if(!r.result) {
										data.inst.refresh();
										var errMsg = '';
										$.each(r.errors, function(key, value){
											errMsg += value + "\n";
										});
										alert(errMsg);
									}
								}
							});
						});
			    	})
			    	.bind("rename.jstree", function (e, data) {
			    		$.post(
		    				"/core/json/renamedepartment", 
		    				{ 
		    					"departmentUUID" : data.rslt.obj[0].id,
		    					"title" : data.rslt.new_name
		    				}, 
		    				function (r) {
		    					if(!r.result) {
		    						$.jstree.rollback(data.rlbk);
		    						$.jstree.rollback(data.rlbk);
									var errMsg = '';
									$.each(r.errors, function(key, value){
										errMsg += value + "\n";
									});
									alert(errMsg);
		    					}
		    				}
		    			);
			    	})
			    	.bind("move_node.jstree", function (e, data) {
			    		data.rslt.o.each(function (i) {
			    			$.ajax({
			    				async	:	false,
			    				type	:	"POST",
			    				url		:	"/core/json/movedepartment",
			    				data : {
									"departmentUUID"	:	$(this)[0].id,
			    				 	"parentDepartment.departmentUUID"	:	data.rslt.cr === -1 ? "" : data.rslt.np[0].id,
			    				 	"sort"	:	data.rslt.cp + i,
			    				 	"title"	:	data.inst.get_text($(this)),
			    				 	"copy"	:	data.rslt.cy ? 1 : 0
								},
								success : function (r) {
									if(!r.result){
										$.jstree.rollback(data.rlbk);
										var errMsg = '';
										$.each(r.errors, function(key, value){
											errMsg += value + "\n";
										});
										alert(errMsg);
									}else{
										$(data.rslt.oc).attr("id", r.obj.departmentUUID);
										if(data.rslt.cy && $(data.rslt.oc).children("UL").length) {
											data.inst.refresh(data.inst._get_parent(data.rslt.oc));
										}
								 	}
								},
								error: function(xhr){
									$.jstree.rollback(data.rlbk);
									$.approval.ajaxerror(xhr);
								}
							});
			    		});
			    	});
    			});	
			});
			
			$("#btnNewDepartment").click(function(){
				$("#departmentTree").jstree("create", null, "last", { "attr" : { "rel" : this.id.toString()} });
			});
			
			$("#btnRenameDepartment").click(function(){
				$("#departmentTree").jstree("rename");
			});
			
			$("#btnRemoveDepartment").click(function(){
				$("#departmentTree").jstree("remove");
			});
			
			$("#btnSaveEmployee").click(function(){		
				$("#frmEmployee").submit();
			});
			
			$("#btnReturnEmployeeList").click(function(){
				$("#area_employee_create").hide();
				$("#area_employee_list").show();
			});
			
			$("#btnNewEmployee").click(function(){
				$('#frmEmployee').each (function(){
					this.reset();
				});
				
				$("#frmEmployee :input[name='operation']").val("create");
				$("#frmEmployee :input[name='employee.employeeUUID']").val("");
			
				$("#area_employee_create").show();
				$("#area_employee_list").hide();
			});
			
			$("#checkAllEmployees").click(function(){
				if($("#checkAllEmployees").is(':checked')){
					$("#employeetable input[name='employeeUUID']").attr("checked", true);
				} else{
					$("#employeetable input[name='employeeUUID']").attr("checked", false);
					$("#employeetable input[name='employeeUUID']").removeClass("jstree-draggable");
				}
				
				if($("#employeetable input:checked[name='employeeUUID']").length > 1){
					$("#employeetable ul[class~='detailline']").removeClass("jstree-draggable");
					$("#employeetable").addClass("jstree-draggable");
				}else{
					$("#employeetable input:checked[name='employeeUUID']").each(function(){
						$("#employeetable #ul_"+ $(this).val()).addClass("jstree-draggable");
					});
					$("#employeetable").removeClass("jstree-draggable");
				}
			});
			
			$("#btnRemoveEmployee").click(function(){
				var employeeUUIDS = "";
				$("#employeetable input:checked[name='employeeUUID']").each(function(){
					employeeUUIDS += $(this).val() + ",";
				});
				if(employeeUUIDS == ""){
					alert("请先选中员工记录");
					return;
				}else if(confirm("您确定将选中员工从该部门挪走吗？")){
					$.ajax({
		    			type: 'POST',
						url: "/core/json/removeemployeesfromdepartment",
						data : { 
							"employeeUUIDS" : employeeUUIDS,
							"departmentUUID" : selectedDepartmentUUID
						}, 
						success : function (r) {
							$.approval.paintemployeetable(r);
						},
						error: function(xhr) {
							$.approval.ajaxerror(xhr);
						}
		    		});
				}
			});
			
			$("#btnSearchEmployeeByKeyword").click(function(){
				var searchKeyword = $("#searchEmployeeByKeyword").val();
				if(searchKeyword == '')
					return;
					
				$.ajax({
	    			type: 'POST',
					url: "/core/json/listemployeeinfo",
					data : { 
						"departmentUUID" : '',
						'keyword' : searchKeyword
					}, 
					success : function (r) {
						$.approval.paintemployeetable(r);
					},
					error: function(xhr) {
						$.approval.ajaxerror(xhr);
					}
	    		});
	    		$("#area_employee_list").show();
				$("#area_employee_create").hide();
			});

			var employeeValidator = $("#frmEmployee").validate({
				submitHandler: function(form) {
					$(form).ajaxSubmit({
						type:"post",
						datatype:"json",
						url: ($("#frmEmployee :input[name='operation']").val() == 'update') ?  "/core/json/updateemployee" : "/core/json/createemployee",
						success: function(data){
							if(data.result){
								alert('success');
							}else{
								var errMsg = '';
								$.each(data.errors, function(key, value){
									errMsg += key+":"+value + "\n";
								});
								alert(errMsg);
								employeeValidator.showErrors(data.errors);
							}
						},
						error: function(){
							alert("服务器处理异常");
						}
					});
				},
				rules:{
					"employee.userId": {
						required:	true,
						email:		true,
						//remote:		"/signup/checkemployeeuserid"
						remote:		{
							url: "/signup/checkemployeeuserid",
							type: "post",
							data: {
								"employee.userId": function() {
									return $("#frmEmployee :input[name='employee.userId']").val();
								},
								"employeeUUID":function(){
									return $("#frmEmployee :input[name='employee.employeeUUID']").val();
								}
							}
						}
					},
					"name":{
						required:	true,
						minlength:	3
					},
					"birth":{
						date: true
					}
				},
				messages: {
					"employee.userId": {
						required:	"电子邮件必须输入",
						email:		"请输入有效的电子邮件地址",
						remote:		"电子邮件已经存在"
					},
					"name":{
						required:	"姓名必须填写",
						minlength:	"姓名长度为2-64位"
					},
					"birth":{
						date: "日期格式：2010-01-01"
					}
				},
				errorElement: "span",
				errorPlacement: function(error, element) {
					error.appendTo(element.parent());
					error.addClass('validatorerror');
				},
				
				onkeyup: false
			});
		});
	}//end if
	else if(menuId == "menu_employee"){
		$("#mainconsole").load("/core/static/employee", {}, function(){
			jQuery.cachedScript("/resources/js/jquery.jstree.js").done(function(){
				$("#demo1").jstree({
		    		core : { /* core options go here */ },
		    		plugins : [ "themes", "html_data", "ui" ],
		    		"themes" : {
		    			"theme"	: "default",
		    			"url"			: "/resources/js/themes/default/style.css"
		    		}
		    	})
		    	.bind("select_node.jstree", function (event, data){
		    		alert(data.rslt.obj.attr("id"));
		    	});
			});
		});
	}
}
</script>

</head>
<body>
	<div id="header" style="height: 60px;"></div>
	<div id="splitline">
		<div id="splitlineleft" class="splitlineleft"></div>
		<div id="splitlineright" class="splitlineright"></div>
	</div>
	<div style="margin:0 auto;clear:both; display:block;">
		<div id="leftmenu" style="clear:both;float: left;width:191px;background-color: #e6f0f7;height:500px;" >
			<div id="quickicon" class="quickicon"><div id="newApproval">NEW</div></div>
			<div id="approvalmenus">
				<div class="lmenu_inactive" id="menu_outbox">提交箱</div>
				<div class="lmenu_active" id="menu_drafts">草稿箱</div>
				<div class="lmenu_inactive" id="menu_pending">未批箱</div>
				<div class="lmenu_inactive" id="menu_notified">通知箱</div>
				<div class="lmenu_inactive" id="menu_preliminary">预审箱</div>
				<div class="lmenu_inactive" id="menu_approved">已批箱</div>
				<div class="lmenu_inactive" id="menu_template">审批样式箱</div>
				<div class="lmenu_inactive" id="menu_approvalline">审批路径管理</div>
				<div class="lmenu_inactive" id="menu_proxy">代理审批人指定</div>
				<div class="lmenu_inactive" id="menu_department">组织结构</div>
				<div class="lmenu_inactive" id="menu_employee">员工管理</div>
			</div>
			
		</div>
		<div id="mainconsole" class="mainconsole">
			
		</div>
	</div>
</body>
</html>